<template>
  <div class="uploadPicture">
    <el-upload ref="upload" :action="url" multiple drag accept=".png,.jpg,.jpeg,.gif" :limit="100" :name="name"
      :on-progress="uploadProcess" :disabled="limit <= pictures.length" :on-success="uploadSuccess"
      :on-error="uploadError" :show-file-list="false" :before-upload="checkUploadFile" v-if="!disabled">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">最多上传{{ limit }}张图片 <span v-show="imgSize">，图片尺寸{{ imgSize }}</span><span
            v-show="fileSize">，文件大小{{ fileSizeText(fileSize) }}以内</span></div>
      </template>
    </el-upload>

    <el-progress v-show="progressFlag" :percentage="loadProgress"></el-progress>

    <draggable class="pictureGroup" v-model="pictures" item-key="index" @end="sortEnd" :disabled="disabled">
      <template #item="{ element }">
        <div class="pictureItem">
          <div class="del" @click.stop="removePictures(element)" v-show="!disabled">
            <el-icon :size="17">
              <Close />
            </el-icon>
          </div>
          <el-image class="img" :src="element" :preview-src-list="pictures" :initial-index="previewIndex(element)">
            <template #placeholder>
              <div class="image_placeholder">加载中</div>
            </template>
          </el-image>
        </div>
      </template>
    </draggable>
  </div>
</template>
<script setup>
import $ from "@util/base"
import { defineProps, defineEmits, ref, watch } from "vue";
import draggable from "vuedraggable"
import { UPLOAD_URL } from "@net/url"
import auth from "@net/auth"
import msg from "@ui/message"
import { ReadBase64Dimension } from "@util/image-dimension"
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  // 上传地址
  url: {
    type: String,
    default: UPLOAD_URL
  },
  // 上传个数
  limit: {
    type: Number,
    default: 1,
  },
  fileSize: {
    type: Number,
    default: null,
  },
  imgSize: {
    type: String,
    default: null
  },
  // 上传文件字段名
  name: {
    type: String,
    default: "file_data",
  },
  disabled: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Array,
    default: () => []
  }
});

const idName = "picture-" + $.uuid8();

const upload = ref(null)
const pictures = ref(props.modelValue || [])
const progressFlag = ref(false)
const loadProgress = ref(0)

watch(() => props.modelValue, val => {
  pictures.value = val || []
})

const headers = { accessToken: auth.getToken() }

function uploadProcess(event) {
  progressFlag.value = true
  loadProgress.value = parseInt(event.percent);

  if (loadProgress.value >= 100) {
    loadProgress.value = 99

  }
}

function checkUploadFile(rawFile) {
  return true
  // if (process.env.NODE_ENV === "production" && (props.imgSize != null || props.fileSize != null)) {
  //   return new Promise((res, rej) => {
  //     loadFile(rawFile, fileBase64 => {
  //       if (props.fileSize != null && rawFile.size > props.fileSize) {
  //         msg.error("图片大小以超过" + fileSizeText(props.fileSize))
  //         rej()
  //         return
  //       }
  //       if (props.imgSize != null) {
  //         let imgSizes = props.imgSize.split("×")
  //         let width = imgSizes[0]
  //         let height = imgSizes[1]
  //         let type = rawFile.name.substring(rawFile.name.lastIndexOf(".") + 1, rawFile.name.length)
  //         let imgWH = ReadBase64Dimension(fileBase64, type)

  //         if (imgWH.width != width || imgWH.height != height) {
  //           msg.error("图片尺寸错误，应为" + props.imgSize)
  //           rej()
  //           return
  //         }
  //       }
  //       res()
  //     })
  //   })
  // } else {
  //   return true
  // }
}

function loadFile(file, callback) {
  var reader = new FileReader();
  reader.onload = function (e) {
    callback(e.target.result)
  }
  reader.readAsDataURL(file)
}

function fileSizeText(value) {
  return parseInt(value / 1024) + "kb"
}


function previewIndex(e) {
  for (let index = 0; index < pictures.value.length; index++) {
    if (e === pictures.value[index]) {
      return index
    }
  }
  return 0
}

function uploadSuccess(response) {
  loadProgress.value = 100
  setTimeout(() => {
    progressFlag.value = false
  }, 1000)
  if (response.code === 0) {
    pictures.value.push(response.data.fileUrl)
    emit('update:modelValue', pictures.value)
  } else {
    let err = ''
    if ($.isNotEmpty(response.msg)) {
      err = "：" + response.msg
    }
    msg.error("图片上传失败" + err)
  }
}

function uploadError() {
  msg.error("图片上传失败")
}

function removePictures(name) {
  pictures.value.remove(e => { return e == name })
  emit('update:modelValue', pictures.value)
}

function sortEnd() {
  emit('update:modelValue', pictures.value)
}

function getPictures() {
  return pictures.value;
}

</script>

<style lang="scss">
.uploadPicture {
  width: 100%;
  padding-bottom: 50px;

  .el-upload {
    width: 100%;
    text-align: left;
  }

  .el-upload__tip {
    text-align: left;
  }

  .pictureGroup {
    display: flex;
    flex-wrap: wrap;

    .image_placeholder {
      display: flex;
      align-items: center;
      justify-content: center;
      background: var(--el-fill-color-light);
      color: var(--el-text-color-secondary);
      width: 120px;
      height: 120px;
    }

    .pictureItem {
      width: 120px;
      height: 120px;
      position: relative;
      margin: 10px;

      &:hover {
        .del {
          display: block;
        }
      }


      // &:not(:first-child) {
      //   margin-left: 20px;
      // }

      .img {
        width: 120px;
        height: 120px;
      }

      .del {
        display: none;
        cursor: pointer;
        top: -6px;
        z-index: 2;
        right: -6px;
        background-color: #fc443e;
        color: #fff;
        position: absolute;
        width: 24px;
        height: 24px;
        line-height: 31px;
        text-align: center;
        border-radius: 50%;
      }
    }
  }
}
</style>
 